package cn.qu.dockman.mgr.disparte;

import cn.qu.dockman.mgr.entity.Host;
import cn.qu.dockman.mgr.entity.Network;
import cn.qu.dockman.mgr.service.HostService;
import cn.qu.dockman.mgr.service.NetworkService;
import cn.qu.dockman.protocol.command.client.NetworkListCommand;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Observable;
import java.util.Observer;

import static cn.qu.dockman.protocol.command.client.NetworkListCommand.NetworkBody;

/**
 * Created by zh on 17/3/16.
 */
public class NetworkListObserver implements Observer {

    public NetworkListObserver(DispartMgr dispartMgr) {
        dispartMgr.addObserver(this);
    }

    @Autowired
    private HostService hostService;

    @Autowired
    private NetworkService networkService;


    @Override
    public void update(Observable o, Object arg) {
        if (arg instanceof ArgDef) {
            ArgDef def = (ArgDef) arg;
            switch (def.getName()) {
                case NetworkListCommand.NAME: {
                    NetworkBody body = (NetworkBody) def.getData();

                    Host host = hostService.findByIp(def.getHost());
                    if (host == null) {
                        break;
                    }
                    Network network = networkService.findNetwork(host.getId(), body.getId());
                    if (network == null) {
                        network = new Network();
                        network.setNetworkId(body.getId());
                        network.setHostId(host.getId());
                    }
                    network.setNetworkDriver(body.getDriver());
                    network.setNetworkName(body.getName());
                    network.setNetworkScope(body.getScope());

                    networkService.saveOrUpdate(network);
                }
                break;
            }
        }
    }
}
